//方案二 不需要修改项目结构 使用outlet管理路由权限 优点 简单高效 好维护
// 思路 先获取当前用户的权限(通过token保存的用户数据) 然后匹配路由 如果没有权限 就返回404页面
import { Outlet, useLocation, Navigate } from "react-router-dom";
import { useEffect, useState } from "react";
import axios from "axios";

//作为路由守卫 我们需要将路由动态创建出来 效果是如果低权限通过网址访问的高权限路由 会报错
export default function OutletDefend() {
  const [allRights, setAllRithts] = useState([]);
  const [userRights, setUserRights] = useState([]);
  const location = useLocation();

  useEffect(() => {
    // 获取所有的权限数据
    const getRights = async () => {
      Promise.all([axios.get("/rights"), axios.get("/children")]).then(
        (res) => {
          setAllRithts([...res[0].data, ...res[1].data]);
        }
      );
    };
    getRights();

    // 获取当前用户权限
    const getUserRights = async () => {
      try {
        const token = JSON.parse(localStorage.getItem("token"));
        if (token && token.role) {
          const res = await axios.get(`/roles/${token.role.id}`);
          setUserRights(res.data.rights || []);
        }
      } catch (error) {
        console.error("获取用户权限失败:", error);
      }
    };

    getUserRights();
  }, []);

  const hasPermission = () => {
    const currentPath = location.pathname;
    // console.log("当前路径：", currentPath);

    // 对于带参数的路由，需要做特殊处理
    const checkPath = currentPath.replace(/\/\d+$/, "/:id");
    // console.log("处理后的路径：", checkPath);

    // 1. 检查用户是否有该路径的权限
    const hasUserRight =
      userRights.includes(checkPath) || userRights.includes(currentPath);
    if (!hasUserRight) {
      return false;
    }

    // 2. 检查该权限的pagepermisson是否为1（启用状态）
    //思路 获取和当前路径匹配的权限信息 然后判断pagepermisson字段
    const rightInfo = allRights.find(
      (item) => item.key === checkPath || item.key === currentPath
    );
    // console.log("权限信息：", rightInfo);

    // 如果找到对应权限，检查pagepermisson字段（routerpermisson字段 专门用来控制新闻预览的权限）
    if (rightInfo && (rightInfo.pagepermisson !== undefined || rightInfo.routerpermisson !== undefined)) {
      return (rightInfo.pagepermisson || rightInfo.routerpermisson) === 1;
    }

    if (rightInfo.pagepermisson === 0) {
      return false;
    }
    // 如果没有pagepermisson字段，默认允许访问
    return true;
  };

  // 如果没有权限，重定向到 404 页面或首页
  if (userRights.length > 0 && !hasPermission()) {
    return <Navigate to="/404" replace />;
  }

  return <Outlet />;
}



/*
import React, { useEffect, useState } from "react";
import { Outlet, Routes, Route } from "react-router-dom";
import axios from "axios";
import Home from "../view/Home/Home";
import UserList from "../view/NewSandBox/User-manage/UserList";
import RoleList from "../view/NewSandBox/Role-manage/RoleList";
import RightList from "../view/NewSandBox/Right-manage/RightList";
import Draft from "../view/NewSandBox/news-manage/Draft";
import Category from "../view/NewSandBox/news-manage/Category";
import NotFund from "../view/404/404";
import { Navigate } from "react-router-dom";
import Published from "../view/NewSandBox/publish-manage/Published";
import Unpublished from "../view/NewSandBox/publish-manage/Unpublished";
import Sunset from "../view/NewSandBox/publish-manage/Sunset";
import NewsList from "../view/NewSandBox/news-manage/NewsList";
import NewsPreview from "../view/NewSandBox/news-manage/NewsPreview";
import Audit from "../view/NewSandBox/audit-manage/Audit";
import AuditList from "../view/NewSandBox/audit-manage/AuditList";
import NewsAdd from "../view/NewSandBox/news-manage/NewsAdd";
//本地路由映射表
const LoaclRouterMap = {
  "/home": <Home />,
  "user-manage/list": <UserList />,
  "role-manage/list": <RoleList />,
  "right-manage/list": <RightList />,
  "news-manage/draft": <Draft />,
  "news-manage/category": <Category />,
  "news-manage/list": <NewsList />,
  "news-manage/preview/:id": <NewsPreview />,
  "news-manage/add": <NewsAdd />,
  "publish-manage/unpublished": <Unpublished />,
  "publish-manage/published": <Published />,
  "publish-manage/sunset": <Sunset />,
  "audit-manage/list": <AuditList />,
  "audit-manage/audit": <Audit />,
  "/": <Navigate to="/home" />,
  "*": <NotFund />,
};
// 动态路由生成 但是对于中小型项目就不推荐这样 我们更推荐使用outlet的方案
export default function OutletDefend() {
  const [userRights, setUserRights] = useState([]);
  useEffect(() => {
    Promise.all([
      axios.get("/rights"),
      axios.get("/roles"),
    ]).then((res) => {
      // setUserRights(res[0].data.concat(res[1].data));
      setUserRights(res[0].data, res[1].data);
    });
  }, []);
  // console.log(userRights);
  return (
    <>
      <Routes>
        {userRights.map((item) => {
          return (
            <Route
              path={item.key}
              element={LoaclRouterMap[item.key]}
              key={item.key}
            ></Route>
          );
        })}
      </Routes>
    </>
  );
}
 */